import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_openim_sdk/flutter_openim_sdk.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:just_audio/just_audio.dart';
import 'package:openim_common/openim_common.dart';

class ChatQuoteView extends StatelessWidget {
  const ChatQuoteView({
    Key? key,
    required this.message,
    required this.isISend,
    this.onTapQuotedMessage,
  }) : super(key: key);

  final Message message;
  final bool isISend;
  final Function(Message)? onTapQuotedMessage;

@override
@override
Widget build(BuildContext context) {
  final quoteElem = message.quoteElem;
  if (quoteElem == null) return const SizedBox.shrink();

  return Container(
    constraints: BoxConstraints(maxWidth: maxWidth),
    child: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 当前回复的内容（主消息，上方）
        if (quoteElem.text?.isNotEmpty == true) 
          Text(
            quoteElem.text!,
            style: TextStyle(
              color: isISend ? Styles.c_000000 : Styles.c_0C1C33,
              fontSize: 16.sp,
              fontWeight: FontWeight.w400,
            ),
          ),
        
        // 间距
        if (quoteElem.text?.isNotEmpty == true) 4.verticalSpace,
        
        // 被引用的消息（下方，灰色小字）
        _buildQuotedMessageText(quoteElem),
      ],
    ),
  );
}

/// 构建引用消息的文本显示（类似微信样式）
Widget _buildQuotedMessageText(QuoteElem quoteElem) {
  final quotedMessage = quoteElem.quoteMessage;
  
  return GestureDetector(
    onTap: () {
      if (quotedMessage != null) {
        _openQuotedContent(quotedMessage);
      }
    },
    child: Container(
      padding: EdgeInsets.symmetric(horizontal: 0, vertical: 2.h),
      child: _buildQuotedContentWithThumbnail(quotedMessage),
    ),
  );
}

/// 构建带缩略图的引用消息内容
Widget _buildQuotedContentWithThumbnail(Message? quotedMessage) {
  if (quotedMessage == null) {
    return Text(
      '[消息已删除]',
      style: TextStyle(
        color: Styles.c_8E9AB0,
        fontSize: 13.sp,
        fontWeight: FontWeight.w400,
      ),
    );
  }

  final contentType = quotedMessage.contentType;
  String senderName = quotedMessage.senderNickname ?? '';
  
  // 图片消息 - 显示缩略图
  if (contentType == MessageType.picture) {
    final pictureElem = quotedMessage.pictureElem;
    final thumbnailUrl = pictureElem?.snapshotPicture?.url;
    
    return Row(
      children: [
        // 缩略图
        if (thumbnailUrl?.isNotEmpty == true)
          Container(
            width: 32.w,
            height: 32.w,
            margin: EdgeInsets.only(right: 6.w),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(4.r),
              color: Styles.c_F0F2F6,
            ),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(4.r),
              child: Image.network(
                thumbnailUrl!,
                fit: BoxFit.cover,
                loadingBuilder: (context, child, loadingProgress) {
                  if (loadingProgress == null) return child;
                  return Container(
                    color: Styles.c_F0F2F6,
                    child: Center(
                      child: SizedBox(
                        width: 12.w,
                        height: 12.w,
                        child: CircularProgressIndicator(
                          strokeWidth: 1.5,
                          valueColor: AlwaysStoppedAnimation<Color>(Styles.c_8E9AB0),
                        ),
                      ),
                    ),
                  );
                },
                errorBuilder: (context, error, stackTrace) {
                  return Container(
                    color: Styles.c_F0F2F6,
                    child: Icon(
                      Icons.image,
                      size: 16.w,
                      color: Styles.c_8E9AB0,
                    ),
                  );
                },
              ),
            ),
          )
        else
          Container(
            width: 32.w,
            height: 32.w,
            margin: EdgeInsets.only(right: 6.w),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(4.r),
              color: Styles.c_F0F2F6,
            ),
            child: Icon(
              Icons.image,
              size: 16.w,
              color: Styles.c_8E9AB0,
            ),
          ),
        // 文本内容
        Expanded(
          child: Text(
            senderName.isNotEmpty ? '$senderName：[图片]' : '[图片]',
            style: TextStyle(
              color: Styles.c_8E9AB0,
              fontSize: 13.sp,
              fontWeight: FontWeight.w400,
            ),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
        ),
      ],
    );
  }
  
  // 视频消息 - 显示缩略图
  if (contentType == MessageType.video) {
    final videoElem = quotedMessage.videoElem;
    final thumbnailUrl = videoElem?.snapshotUrl;
    
    return Row(
      children: [
        // 缩略图
        if (thumbnailUrl?.isNotEmpty == true)
          Container(
            width: 32.w,
            height: 32.w,
            margin: EdgeInsets.only(right: 6.w),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(4.r),
              color: Styles.c_F0F2F6,
            ),
            child: Stack(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.circular(4.r),
                  child: Image.network(
                    thumbnailUrl!,
                    width: 32.w,
                    height: 32.w,
                    fit: BoxFit.cover,
                    loadingBuilder: (context, child, loadingProgress) {
                      if (loadingProgress == null) return child;
                      return Container(
                        color: Styles.c_F0F2F6,
                        child: Center(
                          child: SizedBox(
                            width: 12.w,
                            height: 12.w,
                            child: CircularProgressIndicator(
                              strokeWidth: 1.5,
                              valueColor: AlwaysStoppedAnimation<Color>(Styles.c_8E9AB0),
                            ),
                          ),
                        ),
                      );
                    },
                    errorBuilder: (context, error, stackTrace) {
                      return Container(
                        color: Styles.c_F0F2F6,
                        child: Icon(
                          Icons.videocam,
                          size: 16.w,
                          color: Styles.c_8E9AB0,
                        ),
                      );
                    },
                  ),
                ),
                // 播放按钮覆盖层
                Positioned.fill(
                  child: Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(4.r),
                      color: Colors.black.withOpacity(0.3),
                    ),
                    child: Icon(
                      Icons.play_arrow,
                      color: Colors.white,
                      size: 12.w,
                    ),
                  ),
                ),
              ],
            ),
          )
        else
          Container(
            width: 32.w,
            height: 32.w,
            margin: EdgeInsets.only(right: 6.w),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(4.r),
              color: Styles.c_F0F2F6,
            ),
            child: Stack(
              children: [
                Container(
                  color: Styles.c_F0F2F6,
                  child: Icon(
                    Icons.videocam,
                    size: 16.w,
                    color: Styles.c_8E9AB0,
                  ),
                ),
                Positioned.fill(
                  child: Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(4.r),
                      color: Colors.black.withOpacity(0.3),
                    ),
                    child: Icon(
                      Icons.play_arrow,
                      color: Colors.white,
                      size: 12.w,
                    ),
                  ),
                ),
              ],
            ),
          ),
        // 文本内容
        Expanded(
          child: Text(
            senderName.isNotEmpty ? '$senderName：[视频]' : '[视频]',
            style: TextStyle(
              color: Styles.c_8E9AB0,
              fontSize: 13.sp,
              fontWeight: FontWeight.w400,
            ),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
        ),
      ],
    );
  }
  
  // 其他类型消息 - 只显示文本
  String displayText = '';
  
  switch (contentType) {
    case MessageType.text:
      displayText = quotedMessage.textElem?.content ?? '[文本消息]';
      break;
    case MessageType.voice:
      displayText = '[语音] ${quotedMessage.soundElem?.duration ?? 0}"';
      break;
    case MessageType.file:
      displayText = '[文件] ${quotedMessage.fileElem?.fileName ?? ''}';
      break;
    case MessageType.card:
      displayText = '[名片] ${quotedMessage.cardElem?.nickname ?? ''}';
      break;
    default:
      displayText = '[消息类型: $contentType]';
      break;
  }

  // 组合发送者和消息内容
  String fullText = senderName.isNotEmpty ? '$senderName：$displayText' : displayText;

  return Text(
    fullText,
    style: TextStyle(
      color: Styles.c_8E9AB0,
      fontSize: 13.sp,
      fontWeight: FontWeight.w400,
    ),
    maxLines: 2,
    overflow: TextOverflow.ellipsis,
  );
}

/// 直接打开引用内容的方法
void _openQuotedContent(Message quotedMessage) {
  final contentType = quotedMessage.contentType;
  
  switch (contentType) {
    case MessageType.picture:
      // 直接预览图片
      IMUtils.previewPicture(quotedMessage);
      break;
      
    case MessageType.video:
      // 直接播放视频
      IMUtils.previewMediaFile(
        context: Get.context!,
        message: quotedMessage,
      );
      break;
      
    case MessageType.file:
      // 直接打开文件
      IMUtils.previewFile(quotedMessage);
      break;
      
    case MessageType.text:
    case MessageType.atText:
      // 文本消息显示详细内容
      _showTextContent(quotedMessage);
      break;
      
    case MessageType.voice:
      // 语音消息可以播放（如果有播放功能）
      _showVoiceContent(quotedMessage);
      break;
      
    case MessageType.location:
      // 位置消息显示详细信息
      _showLocationContent(quotedMessage);
      break;
      
    case MessageType.card:
      // 名片消息显示详细信息
      _showCardContent(quotedMessage);
      break;
      
    default:
      // 其他类型消息显示基本信息
      _showMessageInfo(quotedMessage);
      break;
  }
}

/// 显示文本内容的详细信息
void _showTextContent(Message message) {
  final content = message.textElem?.content ?? message.atTextElem?.text ?? '';
  
  if (content.isNotEmpty) {
    Get.dialog(
      AlertDialog(
        title: Text('引用消息内容'),
        content: SingleChildScrollView(
          child: SelectableText(
            content,
            style: TextStyle(fontSize: 16.sp),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: Text('关闭'),
          ),
          TextButton(
            onPressed: () {
              Clipboard.setData(ClipboardData(text: content));
              Get.back();
              IMViews.showToast('已复制到剪贴板');
            },
            child: Text('复制'),
          ),
        ],
      ),
    );
  }
}

/// 显示语音消息信息
void _showVoiceContent(Message message) async {
  final duration = message.soundElem?.duration ?? 0;
  final soundPath = message.soundElem?.soundPath;
  final sourceUrl = message.soundElem?.sourceUrl;
  
  if (soundPath == null && sourceUrl == null) {
    IMViews.showToast('语音文件不存在');
    return;
  }
  
  final audioPlayer = AudioPlayer();
  
  try {
    // 尝试播放音频
    if (soundPath != null && File(soundPath).existsSync()) {
      await audioPlayer.setFilePath(soundPath);
    } else if (sourceUrl != null) {
      await audioPlayer.setUrl(sourceUrl);
    } else {
      IMViews.showToast('语音文件不存在');
      return;
    }
    
    // 播放音频
    await audioPlayer.play();
    // IMViews.showToast('正在播放语音消息');
    
    // 监听播放完成
    audioPlayer.playerStateStream.listen((state) {
      if (state.processingState == ProcessingState.completed) {
        audioPlayer.dispose();
      }
    });
    
  } catch (e) {
    IMViews.showToast('播放失败: $e');
    audioPlayer.dispose();
  }
}
/// 显示位置消息信息
void _showLocationContent(Message message) {
  final locationElem = message.locationElem;
  if (locationElem == null) return;
  
  Get.dialog(
    AlertDialog(
      title: Text('位置信息'),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Icon(Icons.location_on, size: 48.w, color: Styles.c_0089FF),
          8.verticalSpace,
          if (locationElem.description?.isNotEmpty == true) ...[
            Text('描述: ${locationElem.description}'),
            8.verticalSpace,
          ],
          Text('纬度: ${locationElem.latitude}'),
          4.verticalSpace,
          Text('经度: ${locationElem.longitude}'),
        ],
      ),
      actions: [
        TextButton(
          onPressed: () => Get.back(),
          child: Text('关闭'),
        ),
      ],
    ),
  );
}

/// 显示名片消息信息
void _showCardContent(Message message) {
  final cardElem = message.cardElem;
  if (cardElem == null) return;
  
  Get.dialog(
    AlertDialog(
      title: Text('名片信息'),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 头像
          if (cardElem.faceURL?.isNotEmpty == true)
            CircleAvatar(
              radius: 30.w,
              backgroundImage: NetworkImage(cardElem.faceURL!),
            )
          else
            CircleAvatar(
              radius: 30.w,
              child: Icon(Icons.person, size: 30.w),
            ),
          12.verticalSpace,
          // 昵称
          Text(
            cardElem.nickname ?? '未知用户',
            style: TextStyle(fontSize: 18.sp, fontWeight: FontWeight.bold),
          ),
          8.verticalSpace,
          // 用户ID
          Text(
            'ID: ${cardElem.userID ?? ''}',
            style: TextStyle(fontSize: 14.sp, color: Styles.c_8E9AB0),
          ),
        ],
      ),
      actions: [
        TextButton(
          onPressed: () => Get.back(),
          child: Text('关闭'),
        ),
        TextButton(
          onPressed: () {
            Get.back();
            // 可以添加查看用户资料的逻辑
            if (cardElem.userID?.isNotEmpty == true) {
              // 这里可以调用查看用户资料的方法
              IMViews.showToast('查看用户资料功能待实现');
            }
          },
          child: Text('查看资料'),
        ),
      ],
    ),
  );
}

/// 显示消息基本信息
void _showMessageInfo(Message message) {
  Get.dialog(
    AlertDialog(
      title: Text('消息信息'),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('消息类型: ${_getMessageTypeName(message.contentType)}'),
          8.verticalSpace,
          Text('发送者: ${message.senderNickname ?? '未知'}'),
          8.verticalSpace,
          Text('发送时间: ${IMUtils.getChatTimeline(message.sendTime ?? 0)}'),
        ],
      ),
      actions: [
        TextButton(
          onPressed: () => Get.back(),
          child: Text('关闭'),
        ),
      ],
    ),
  );
}

/// 获取消息类型名称
String _getMessageTypeName(int? contentType) {
  switch (contentType) {
    case MessageType.text:
      return '文本消息';
    case MessageType.picture:
      return '图片消息';
    case MessageType.video:
      return '视频消息';
    case MessageType.voice:
      return '语音消息';
    case MessageType.file:
      return '文件消息';
    case MessageType.location:
      return '位置消息';
    case MessageType.card:
      return '名片消息';
    case MessageType.quote:
      return '引用消息';
    case MessageType.atText:
      return '@消息';
    case MessageType.customFace:
      return '表情消息';
    default:
      return '未知类型';
  }
}
}